<template>
  
      <bubbleMenu />
<!-- <el-button type="warning" @click="addComment">添加批注</el-button> -->
        <div class="editcont">
          <EditorContent
          style="padding: 8px;  overflow-y: auto;"
          :editor="editor"
        />
      </div>
      <!-- <FloatingMenu/> -->
        <!-- <el-button @click="addComment" type="warning">添加批注</el-button> -->

</template>
<script lang="ts" setup>
import bubbleMenu from '@/components/index-center/bubble-menu/index1.vue';
import { defineComponent, onMounted, onBeforeUnmount, ref, watch, nextTick } from 'vue';
import { Editor, EditorContent, useEditor } from '@tiptap/vue-3';
import Underline from '@tiptap/extension-underline'
// 列表
import { Markdown } from 'tiptap-markdown';
import ListItem from '@tiptap/extension-list-item'
import OrderedList from '@tiptap/extension-ordered-list'
import BulletList from '@tiptap/extension-bullet-list'
import Highlight from '@tiptap/extension-highlight'
// 代码
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import css from 'highlight.js/lib/languages/css'
import js from 'highlight.js/lib/languages/javascript'
import ts from 'highlight.js/lib/languages/typescript'
import html from 'highlight.js/lib/languages/xml'
import { common, createLowlight } from 'lowlight'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import TaskItem from '@tiptap/extension-task-item'
import TaskList from '@tiptap/extension-task-list'
import { useEditorStore } from '@/stores/editStore'
import { currentNodeInfo } from '@/stores/currentNodeStore';
import { loadHeadings } from '../index-left/index-dagang/dagang';
import { TabIndent } from '@/tiptap/extensions/TabPlugin';
import { useCommentPluginStore } from '@/stores/commentPluginStore';
import { ExtendedImage } from '@/tiptap/extensions/ExtendedImage'
import { ShortcutCopyPlugin } from '@/tiptap/extensions/ShortcutCopyPlugin'
import MathExtension from '@/tiptap/extensions/mathExtension';
import { Customkeys } from '@/tiptap/extensions/keyExtension';
const lowlight = createLowlight()
lowlight.register({ html, ts, css, js })


const editorStore = useEditorStore()
const currentNode = currentNodeInfo()
  const commentPlugin = useCommentPluginStore().getPlugin()
// 使用ref创建可变的响应式引用
// 编辑器初始化
// 如果是粘贴，则修改这个值
let gloable_editor = false
const editor = useEditor({
  //是否可编辑
  editable: true,
  content: ``,

  extensions: [
    ExtendedImage,
    Underline,
    Markdown,
    TabIndent,
    StarterKit.configure({
      heading: {
        levels: [1, 2, 3, 4, 5],
      },
      codeBlock: false,  // ✅ 禁用 StarterKit 的 code_block
    }),
    Highlight.configure({ 
      multicolor: true
      }),
    Customkeys,
    TaskList,
    TaskItem,
    Placeholder.configure({
      placeholder: '请输入文本 …'
    }),
    OrderedList,
    BulletList,
    ListItem,
    CodeBlockLowlight.configure({
      lowlight,
      defaultLanguage: 'javascript',
    }),
      MathExtension.configure({
      evaluation: true, // 开启公式计算功能
      addInlineMath: true, // 添加内联数学节点
      delimiters: "dollar", // 使用美元符号作为公式分隔符
      renderTextMode: "raw-latex" // 以原始 LaTeX 格式显示文本
    }),

  ],

  editorProps: {
handlePaste(view, event) {
  const items = Array.from(event.clipboardData?.items || [])
  for (const item of items) {
    if (item.type.indexOf('image') === 0) {
      const file = item.getAsFile()
      if (!file) return false
      const sizeMB = file.size / 1024 / 1024
      if (sizeMB > 10) {
        alert('图片必须小于 10MB')
        return true
      }

      // ✅ 先上传再插入
      uploadImage(file)
        .then((realPath) => {
          const finalUrl = realPath.startsWith('http')
            ? realPath
            : `http://localhost:8080/api${realPath}`
          const { schema, tr } = view.state
          const imageNode = schema.nodes.image.create({
            src: finalUrl,
            draggable: true
          })

          const insertPos = tr.selection.from
          view.dispatch(tr.insert(insertPos, imageNode))
        })
        .catch((err) => {
          console.error('图片上传失败', err)
          alert('图片上传失败，请检查文件格式或网络')
        })

      return true
    }
  }
  return false
},

},
onCreate({ editor }) {
    loadHeadings()
    editorStore.setEditorInstance(editor)
    editor.registerPlugin(ShortcutCopyPlugin(editor))
},
  onUpdate({ editor }) {
    console.log("粘贴时候，触发这个吧",editor);

    var node = editor.state.doc.resolve(editor.state.selection.from).parent
    // console.log("当前光标所在的node",node);
    //只有当前操作的这个节点，是在标题或者是在新增标题，才需要重新加载标题
    if (node.attrs && node.attrs.level) {
      loadHeadings()
    }
    // console.log(editor.getText());
    //改完一次就加载一次标题
    //标签存到pinia
      console.log("更新后触发：",gloable_editor);

    if(gloable_editor){
      loadHeadings()
    }
    editorStore.setEditor(editor, editor.getHTML())
  },
  onPaste() {
    // 如果粘贴则，调用onUpdate方法
    console.log("粘贴先触发？");
    gloable_editor = true

  },
  injectCSS: false,
})
// 保存按钮






onMounted(() => {
  //同步操作 后期初始库内容
  nextTick(() => {

    if (editor.value) {
      //  等editor初始化后载入 pinia存的持久化html信息 第二个参数表示是否存JSON
      editor.value.commands.setContent(currentNode.nodehtml,false)
    setTimeout(() => {
        loadHeadings();
      }, 100);
    }

  });
})

onBeforeUnmount(() => {
  console.log("执行销毁")
  editor.value?.destroy()
})

//请求后端保存图片到本地
const uploadImage = async (file: File): Promise<string> => {
  const formData = new FormData()
  formData.append('file', file)

  const response = await fetch('http://localhost:8080/api/upload/image', {
    method: 'POST',
    body: formData,
  })

  if (!response.ok) {
    throw new Error('上传失败')
  }

  const result = await response.json()
  return result.url // 返回后端生成的图片 URL
}
import img from '@/assets/bg.png'
</script>
<style>
.openai-button {
  position: fixed;
  background-color: #d4b5cb;
  top: 20px;
  right: 5%;
  z-index: 1000;
  border-radius: 50%;
}
.ProseMirror img{
  user-select: all;
  pointer-events: auto;
  max-width: 100%;
}
.ProseMirror img.selected-image{
  outline: 2px solid #409EFF;
}


/* .EditMain{
    position: relative;
    width:100vw;
    height: 100vh;

    display: grid;
    grid-template-columns: 20% 60% 20%;

  } */

strong {
  font-weight: bold;
  /* 加粗（默认） */
  /* color: #ff0000; */
  /* 红色 */
  font-size: 18px;
  /* 字号 */
  /* background-color: #fffacd; */
  /* 浅黄色背景 */
  padding: 2px 5px;
  /* 内边距 */
  border-radius: 3px;
  /* 圆角 */
}



.editcont {
  position: relative;
  /* width: 100vw;
    height: 100vh; */
  overflow: hidden;
  /* background-image: url('@/assets/bg.png');
  z-index: 100; */
}

</style>

<style lang="scss">
b {
  font-weight: bold;
}

.tiptap-comment {
  background-color: rgba(255, 230, 0, 0.4);
  border-bottom: 1px dashed orange;
  cursor: pointer;
}


.ProseMirror {
  overflow-y: auto; // 改为 auto 只在需要时显示滚动条
  /// 编辑器滚动效果  以下是AI生成的
  height: 83.5vh; // 必须设置固定高度或最大高度
  min-height: 500px; // 可选，确保最小高度
  padding: 0px 80px; // 添加内边距
  background: #f5ecec; // 背景色
  // 自定义滚动条样式
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
  border-radius: 18px;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #c1c1c1;
    border-radius: 4px;
  }
}

.ProseMirror p {
  margin: 0;
  color: #333
}

.ProseMirror:focus {
  outline: none;
}

.tiptap p.is-editor-empty:first-child::before {
  color: #adb5bd;
  content: attr(data-placeholder);
  float: left;
  height: 0;
  pointer-events: none;
}

.tiptap {
  >*+* {
    margin-top: 0.75em;
  }

  ul {
    padding: 0 2rem;
    list-style: square;
  }

  ol {
    padding: 0 2rem;
    list-style: decimal;
  }

  table {
    border-collapse: collapse;
    table-layout: fixed;
    width: 100%;
    margin: 0;
    overflow: hidden;

    td,
    th {
      min-width: 1em;
      border: 2px solid #ced4da;
      padding: 3px 5px;
      vertical-align: top;
      box-sizing: border-box;
      position: relative;

      >* {
        margin-bottom: 0;
      }
    }

    th {
      font-weight: bold;
      text-align: left;
      background-color: #f1f3f5;
    }

    .selectedCell:after {
      z-index: 2;
      position: absolute;
      content: '';
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background: rgba(200, 200, 255, 0.4);
      pointer-events: none;
    }

    .column-resize-handle {
      position: absolute;
      right: -2px;
      top: 0;
      bottom: -2px;
      width: 4px;
      background-color: #adf;
      pointer-events: none;
    }

    p {
      margin: 0;
    }
  }

  pre {
    background: #0d0d0d;
    color: #fff;
    font-family: 'JetBrainsMono', monospace;
    padding: 0.75rem 1rem;
    border-radius: 0.5rem;

    code {
      color: inherit;
      padding: 0;
      background: none;
      font-size: 0.8rem;
    }

    .hljs-comment,
    .hljs-quote {
      color: #616161;
    }

    .hljs-variable,
    .hljs-template-variable,
    .hljs-attribute,
    .hljs-tag,
    .hljs-name,
    .hljs-regexp,
    .hljs-link,
    .hljs-name,
    .hljs-selector-id,
    .hljs-selector-class {
      color: #f98181;
    }

    .hljs-number,
    .hljs-meta,
    .hljs-built_in,
    .hljs-builtin-name,
    .hljs-literal,
    .hljs-type,
    .hljs-params {
      color: #fbbc88;
    }

    .hljs-string,
    .hljs-symbol,
    .hljs-bullet {
      color: #b9f18d;
    }

    .hljs-title,
    .hljs-section {
      color: #faf594;
    }

    .hljs-keyword,
    .hljs-selector-tag {
      color: #70cff8;
    }

    .hljs-emphasis {
      font-style: italic;
    }

    .hljs-strong {
      font-weight: 700;
    }
  }
}

.tableWrapper {
  overflow-x: auto;
}

.resize-cursor {
  cursor: ew-resize;
  cursor: col-resize;
}

.paragraph-class {
  margin: 0 0 1rem 0; // 默认 margin
  line-height: 1.6;

  // 嵌套选择器（SCSS 特性）
  &:first-child {
    margin-top: 0;
  }

  &:last-child {
    margin-bottom: 0;
  }

  // 特定情况下的段落样式
  &.has-dropcap::first-letter {
    float: left;
    font-size: 3em;
    line-height: 1;
    margin-right: 0.5rem;
    font-weight: bold;
  }

  // 暗黑模式适配
  .dark & {
    color: #e2e8f0;
  }
}

.tiptap-blockquote {
  border-left: 4px solid #fd0d99;
  background: #f8f9fa;
  padding: 0.5rem 1rem;
  margin: 1rem 0;
}
</style>
